<?php
set_include_path(".;C:/wamp/www/TEAMEKA/application/Online");
require_once 'config.php';

function html($string)
{
	return utf8_encode(htmlspecialchars($string, ENT_QUOTES));
}

function url_format($string)
{
	$string = str_replace(' ', '-', strtolower($string));
	return html(preg_replace('#[^a-z0-9-]#', '', $string));
}

function generic_autoload($class)
{
	require_once str_replace('_', '/', $class). '.php';
}

//Suppliers
function createSupplier()
{
	//
	clearSupplierCookies();
	$name = checkCtype_Print($_POST['newSupplierName']);
	$phone = checkCtype_Print($_POST['newSupplierPhone']);
	if (empty($name) or ($name === " "))
	{
		setcookie("SupplierName","EmptyName");
	}
	else if (empty($phone) or ($phone === " ") or (!checkPhoneFormat($phone)))
	{
		setcookie("SupplierPhone","InvalidPhone");
	}
	else 
	{
		$supplierArray = array(':supplier_name' => $name, ':supplier_phone' => $phone);
		$modelSupplier = new Model_SupplierContacts();
		$id = $modelSupplier->createNewSupplierContact($supplierArray);
		if ($id == -1)
		{
			setcookie("CreateSupplier","Unsuccessful");
		}
	}
	header('Location: '.html($_SERVER['HTTP_ROOT']).'supplier');
}
function updateSupplier()
{
	clearSupplierCookies();
	$supplier = getSupplierArray();
	if (empty($supplier))
	{
		header('Location: '.html($_SERVER['HTTP_ROOT']).'supplier');
	}
	else 
	{
		$modelSupplier = new Model_SupplierContacts();
		$count = $modelSupplier->updateSupplierContact($supplier);
		if ($count === 0)
		{
			setcookie("UpdateSupplier","Unsuccessful");
		}
		header('Location: '.html($_SERVER['HTTP_ROOT']).'supplier');
	}
}
function deleteSupplier()
{
	clearSupplierCookies();
	$id = checkCtype_Digit($_POST['supplierSelectedId']);
	if (empty($id) or $id === " ")
	{
		return null;
	}
	else
	{
		$modelSupplier = new Model_SupplierContacts();
		$count = $modelSupplier->deleteSupplierContact($id);
		if ($count !== 1)
		{
			setcookie("DeleteSupplier","Unsuccessful");
		}
		header('Location: '.html($_SERVER['HTTP_ROOT']).'supplier');
	}
}
function clearSupplierCookies()
{
	if (isset($_COOKIE["SupplierPhone"]))
	{
		setcookie('SupplierPhone');
	}
	if (isset($_COOKIE["SupplierName"]))
	{
		setcookie('SupplierName');
	}
	if (isset($_COOKIE["DeleteSupplier"]))
	{
		setcookie('DeleteSupplier');
	}
	if (isset($_COOKIE["CreateSupplier"]))
	{
		setcookie('CreateSupplier');
	}
	if (isset($_COOKIE["UpdateSupplier"]))
	{
		setcookie('UpdateSupplier');
	}
}
//Inventory
function createInventoryItem()
{
	clearInventoryCookies();
	$product_name = checkCtype_Print($_POST['newItemName']);
	$product_description = checkCtype_Print($_POST['newItemDescription']);
	$product_quantity = checkCtype_Digit($_POST['newItemQuantity']);
	if (empty($product_name) or ($product_name === " "))
	{
		setcookie("ProductName","EmptyName");
	}
	else if (empty($product_description) or ($product_description === " "))
	{
		setcookie("ProductDescription","EmptyDescription");
	}
	else if ( $product_quantity === null)
	{
		setcookie("ProductQuantity","InvalidQuantity");
	}
	else if ( empty($product_quantity) or ($product_quantity === " "))
	{
		setcookie("ProductQuantity","EmptyQuantity");
	}
	else if ( $product_quantity < 0)
	{
		setcookie("ProductQuantity","NegativeQuantity");
	}
	else 
	{
		$inventoryArray = array(':product_quantity' => $product_quantity, ':product_description' => $product_description, ':product_name' => $product_name);
		$modelInventory = new Model_Inventory();
		$id = $modelInventory->createNewInventoryItem($inventoryArray);
		if ($id == -1)
		{
			setcookie("CreateInventory","Unsuccessfull");
		}
	}
	header('Location: '.html($_SERVER['HTTP_ROOT']).'inventory');
}
function updateInventoryItem($inventoryAction)
{
	clearInventoryCookies();
	$inventoryArray = getInventoryArray();
	if (empty($inventoryArray))
	{
		header('Location: '.html($_SERVER['HTTP_ROOT']).'inventory');
	}
	else
	{
		if($inventoryAction=='plus')
		{
			$inventoryArray[":product_quantity"]+=1;
		}
		if($inventoryAction=='minus')
		{
			$inventoryArray[":product_quantity"]-=1;
		}
		$modelInventory = new Model_Inventory();
		$count = $modelInventory->updateInventoryItem($inventoryArray);
		if ($count === 0)
		{
			setcookie("UpdateInventory","Unsuccessfull");
		}
		header('Location: '.html($_SERVER['HTTP_ROOT']).'inventory');
	}
}
function deleteInventoryItem()
{
	clearInventoryCookies();
	$id = checkCtype_Digit($_POST['inventorySelectedId']);
	if (empty($id) or ($id === " "))
	{
		return null;
	}
	else
	{
		$modelInventory = new Model_Inventory();
		$count = $modelInventory->deleteInventoryItem($id);
		if ($count !== 1)
		{
			setcookie("DeleteInventory","Unsuccessfull");
		}
		header('Location: '.html($_SERVER['HTTP_ROOT']).'inventory');
	}
}
function clearInventoryCookies()
{
	if (isset($_COOKIE["ProductName"]))
	{
		setcookie('ProductName');
	}
	if (isset($_COOKIE["ProductDescription"]))
	{
		setcookie('ProductDescription');
	}
	if (isset($_COOKIE["ProductQuantity"]))
	{
		setcookie('ProductQuantity');
	}
	if (isset($_COOKIE["CreateInventory"]))
	{
		setcookie('CreateInventory');
	}
	if (isset($_COOKIE["UpdateInventory"]))
	{
		setcookie('UpdateInventory');
	}
	if (isset($_COOKIE["DeleteInventory"]))
	{
		setcookie('DeleteInventory');
	}
}
//profile
function searchProfile() 
{ 
	clearProfileCookies();
	$targetProfile = $_POST['searchClientInput'];
	if(empty($targetProfile) or ($targetProfile === " ") or (!checkPhoneFormat($targetProfile))) 
 	{ 
 		setcookie("ProfilePhone","InvalidPhone");
 		header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
	} 
	else 
	{ 
		session_start();
		$_SESSION['searchProfilePhone'] = $targetProfile;
		$_SESSION['lastURI'] = $_SERVER['REQUEST_URI'];
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/search');
	} 
}
function createProfile()
{
	clearProfileCookies();
	if (!isset($_POST['c_sex']))
	{
		setcookie("ProfileGender","EmptyGender");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
	}
	else 
	{
		if (checkCtype_Print($_POST['c_sex']) === "Male")
		{
			$gender = 'M';
		}
		else
		{
			$gender = 'F';
		}
		$first_name = checkCtype_Print($_POST['c_fname']);
		if (empty($first_name) or ($first_name === " "))
		{
			setcookie("ProfileFName","EmptyFName");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
		}
		else 
		{
			$last_name = checkCtype_Print($_POST['c_lname']);
			if (empty($last_name) or ($last_name === " "))
			{
				setcookie("ProfileLName","EmptyLName");
				header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
			}
			else 
			{
				$home_phone_number = $_POST['c_hphone'];
				if (!checkPhoneFormat($home_phone_number))
				{
					setcookie("ProfileHomePhone","InvalidPhone");
					header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
				}
				else 
				{
					$email = checkCtype_Email($_POST['c_email']);
					$role = null;
					$cell_phone_number = $_POST['c_cphone'];
					if (!checkPhoneFormat($cell_phone_number))
					{
						setcookie("ProfileCellPhone","InvalidPhone");
						header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
					}
					else
					{
						if (checkCtype_Print($_POST['note0']) === "Yes")
						{
							$tire_set_stored = 1;
						}
						else
						{
							$tire_set_stored = 0;
						}
						$creation_date = date("Y-m-d");
						$modification_date = date("Y-m-d");
	
						$carrier = $_POST['cell_phone_carrier'];
						if(isset($_POST['sendNoteToCell']))
						{
							$send_to_cell_phone = 1;
							$cell_phone_carrier = sendTextToPhoneAddress($cell_phone_number, $carrier);
						}
						else 
						{
							$send_to_cell_phone = 0;
							$cell_phone_carrier = null;
						}
						if ( isset($_POST['sendNoteToEmail']))
						{
							$send_to_email = 1;
						}
						else
						{
							$send_to_email = 0;
						}
						if (checkCtype_Print($_POST['note1']) === "Yes")
						{
							$note1 = 1;
						}
						else 
						{
							$note1 = 0;
						}
						if (checkCtype_Print($_POST['note2']) === "Yes")
						{
							$note2 = 1;
						}
						else 
						{
							$note2 = 0;
 						}
						if (checkCtype_Print($_POST['note3']) === "Yes")
						{
							$note3 = 1;
						}
						else
						{
							$note3 = 0;
						}
	
						$profileArray = array(':first_name'=>$first_name, ':last_name'=>$last_name, ':home_phone_number'=>$home_phone_number, ':email'=>$email, 
							':role'=> $role, ':gender'=>$gender,':cell_phone_number'=>$cell_phone_number, ':cell_phone_carrier'=>$cell_phone_carrier,
							':tire_set_stored' => $tire_set_stored, ':creation_date' => $creation_date, ':modification_date' => $modification_date,
							':send_to_cell_phone' => $send_to_cell_phone, ':send_to_email' => $send_to_email, ':note1' => $note1,
							':note2' => $note2, ':note3' => $note3);
						$modelProfile = new Model_Profile();
						$id = $modelProfile->createNewProfile($profileArray);
						if ($id != -1)
						{
							if ($id === -2)
							{
								setcookie("ProfileHomePhone","ExistingPhone");
								header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
							}
							else 
							{
								session_start();
								$_SESSION['createdPersonId'] = $id;
								session_write_close();
								header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/create');
							}
						}
						else 
						{
							setcookie("CreateProfile","Unsuccessful");
							header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
						}
					}
				}
			}
		}
						
	}
}
function updateProfile()
{
	clearProfileCookies();
	$profile = getProfileArray();
	if (empty($profile))
	{
		header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
	}
	else 
	{
		$modelProfile = new Model_Profile();
		$count = $modelProfile->updateProfile($profile);
		if ($count !== 0)
		{
			session_start();
			$_SESSION['searchProfilePhone'] = $profile[':home_phone_number'];
			$_SESSION['lastURI'] = $_SERVER['REQUEST_URI'];
			session_write_close();
			header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/search');
		}
		else if ($count === 0)
		{
			setcookie("UpdateProfile","Unsuccessful");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
		}
	}
}
function deleteProfile()
{
	clearProfileCookies();
	$id = checkCtype_Digit($_POST['personId']);
	if (empty($id) or $id === " ")
	{
		return null;
	}
	else
	{
		$modelPerson = new Model_Person();
		$count = $modelPerson->deletePerson($id);
		if ($count === 1)
		{
			session_start();
			if (isset($_SESSION['searchProfilePhone']))
			{
				unset($_SESSION['searchProfilePhone']);
			}
			if (isset($_SESSION['createdPersonId']))
			{
				unset($_SESSION['createdPersonId']);
			}
			if (isset($_SESSION['selectedCarIndex']))
			{
				unset($_SESSION['selectedCarIndex']);
			}
			if (isset($_SESSION['phone']))
			{
				unset($_SESSION['phone']);
			}
			if (isset($_SESSION['lastURI']))
			{
				unset($_SESSION['lastURI']);
			}
			session_write_close();
		}
		else 
		{
			setcookie("DeleteProfile","Unsuccessful");
		}
		header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
	}
}
function selectedCar()
{
	clearProfileCookies();
	$carId = $_POST['selectedCarIndex'];
	$personPhoneNumber = $_POST['profileId'];
	if(empty($personPhoneNumber) or ($personPhoneNumber === " ") or (!checkPhoneFormat($personPhoneNumber)))
	{
		setcookie("ProfilePhone","InvalidPhone");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
	}
	else if (($carId === " "))
	{
		setcookie("CarIndex","EmptyIndex");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
	}
	else
	{
		session_start();
		$_SESSION['selectedCarIndex'] = $carId;
		$_SESSION['phone'] = $_POST['profileId'];
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/car');
	}
}
function createCar()
{
	clearProfileCookies();
	$profileId = checkCtype_Digit($_POST['client_id']);
	if (empty($profileId) or ($profileId === " "))
	{
		return null;
	}
	else
	{
		$car_history = checkCtype_Print($_POST['carHistory']);
		$make = checkCtype_Print($_POST['carMake']);
		if (empty($make) or ($make === " "))
		{
			setcookie("CarMake","EmptyMake");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
		}
		else 
		{
			$model = checkCtype_Print($_POST['carModel']);
			if (empty($model) or ($model === " "))
			{
				setcookie("CarModel","EmptyModel");
				header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
			}
			else 
			{
				$year = checkCtype_Digit($_POST['carYear']);
				if (empty($year) or ($year === " "))
				{
					setcookie("CarYear","EmptyYear");
					header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
				}
				else if (($year === null) or (strlen($year) !== 4) or ($year > checkCtype_Digit(date("Y"))))
				{
					setcookie("CarYear","InvalidYear");
					header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
				}
				else 
				{
					$last_oil_change_date = $_POST['lastOilChanged'];
					if ( ((!empty($last_oil_change_date)) or (!$last_oil_change_date === " ")) and (!checkDateFormat($last_oil_change_date)) )
					{
						setcookie("LastOilChangeDate","InvalidLastOilChangeDate");
						header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
					}
					else
					{
						$carArray = array(':profile_id' => $profileId, ':car_history'=>$car_history, ':make'=>$make, ':model'=>$model, ':year'=>$year,
							':last_oil_change_date'=> $last_oil_change_date);
						$modelCar = new Model_Car();
						$id = $modelCar->createNewCar($carArray);
						if ($id != -1)
						{
							session_start();
							$_SESSION['selectedCarIndex'] = $_POST['selectedCarIndex'];
							$_SESSION['phone'] = $_POST['profileId'];
							session_write_close();
							header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/car');
						}
						else 
						{
							setcookie("CreateCar","Unsuccessful");
							header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
						}
					}
				}
			}
		}
	}
}
function updateCar()
{
	clearProfileCookies();
	$car = getCarArray();
	if (empty($car))
	{
		header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/car');
	}
	else 
	{
		$modelCar = new Model_Car();
		$count = $modelCar->updateCar($car);
		if ($count === 1)
		{
			session_start();
			$_SESSION['selectedCarIndex'] = $_POST['selectedCarIndex'];
			$_SESSION['phone'] = $_POST['profileId'];
			session_write_close();
			header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/car');
		}
		else if ($count === 0)
		{
			setcookie("UpdateCar","Unsuccessful");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
		}
	}
}
function deleteCar()
{
	clearProfileCookies();
	$carId = checkCtype_Digit($_POST['carSelectedId']);
	if (empty($carId) or ($carId === " "))
	{
		return null;
	}
	else
	{
		$modelCar = new Model_Car();
		$count = $modelCar->deleteCar($carId);
		if ($count === 1)
		{
			session_start();
			if (isset($_SESSION['selectedCarIndex']))
			{
				unset($_SESSION['selectedCarIndex']);
			}
			session_write_close();
		}
		else 
		{
			setcookie("DeleteCar","Unsuccessful");
		}
		header('Location: '.html($_SERVER['HTTP_ROOT']).'profile/');
	}
}
function clearProfileCookies()
{
	if (isset($_COOKIE["ProfilePhone"]))
	{
		setcookie('ProfilePhone');
	}
	if (isset($_COOKIE["SearchProfile"]))
	{
		setcookie('SearchProfile');
	}
	if (isset($_COOKIE["ProfileGender"]))
	{
		setcookie('ProfileGender');
	}
	if (isset($_COOKIE["ProfileFName"]))
	{
		setcookie('ProfileFName');
	}
	if (isset($_COOKIE["ProfileLName"]))
	{
		setcookie('ProfileLName');
	}
	if (isset($_COOKIE["ProfileHomePhone"]))
	{
		setcookie('ProfileHomePhone');
	}
	if (isset($_COOKIE["ProfileCellPhone"]))
	{
		setcookie('ProfileCellPhone');
	}
	if (isset($_COOKIE["CreateProfile"]))
	{
		setcookie('CreateProfile');
	}
	if (isset($_COOKIE["UpdateProfile"]))
	{
		setcookie('UpdateProfile');
	}
	if (isset($_COOKIE["DeleteProfile"]))
	{
		setcookie('DeleteProfile');
	}
	if (isset($_COOKIE["CarIndex"]))
	{
		setcookie('CarIndex');
	}
	if (isset($_COOKIE["CarHistory"]))
	{
		setcookie('CarHistory');
	}
	if (isset($_COOKIE["CarMake"]))
	{
		setcookie('CarMake');
	}
	if (isset($_COOKIE["CarModel"]))
	{
		setcookie('CarModel');
	}
	if (isset($_COOKIE["CarYear"]))
	{
		setcookie('CarYear');
	}
	if (isset($_COOKIE["LastOilChangeDate"]))
	{
		setcookie('LastOilChangeDate');
	}
	if (isset($_COOKIE["CreateCar"]))
	{
		setcookie('CreateCar');
	}
	if (isset($_COOKIE["UpdateCar"]))
	{
		setcookie('UpdateCar');
	}
	if (isset($_COOKIE["DeleteCar"]))
	{
		setcookie('DeleteCar');
	}
}
//Appointment
function searchAppointment()
{
	clearAppointmentCookies();
	$targetProfile = $_POST['searchAppointmentInput'];
	if(empty($targetProfile) or ($targetProfile === " ") or (!checkPhoneFormat($targetProfile)))
	{
		setcookie("AppointmentPhone","InvalidPhone");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
	}
	else
	{
		session_start();
		$_SESSION['searchProfilePhone'] = $targetProfile;
		$_SESSION['date'] = $_POST['currentDate'];
		$_SESSION['lastURI'] = $_SERVER['REQUEST_URI'];
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/search');
	}
}
function createAppointment()
{
	clearAppointmentCookies();
	$clientId = checkCtype_Digit($_POST['apt_clientId']);
	if (empty($clientId) or ($clientId === " "))
	{
		return null;
	}
	else 
	{
		$date = $_POST['apt_appointmentDate'];
		if (empty($date) or ($date === " ") or ($date === "0000-00-00"))
		{
			setcookie("Date","EmptyDate");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
		}
		else if (!checkDateFormat($date) or (strtotime($date) < time())) 
		{
			setcookie("Date","InvalidDate");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
		}
		else 
		{
			$start_time = $_POST['apt_startTime'];
			if (empty($start_time) or ($start_time === " "))
			{
				setcookie("StartTime","EmptyStartTime");
				header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
			}
			else 
			{
				$end_time = $_POST['apt_endTime'];
				if (empty($end_time) or ($end_time === " "))
				{
					setcookie("EndTime","EmptyEndTime");
					header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
				}
				else 
				{
					if ($start_time >= $end_time)
					{
						setcookie("TimeSlot","InvalidTimeSlot");
						header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
					}
					else 
					{
						$total_estimate_time = $_POST['apt_estTime'];
						if (empty($total_estimate_time) or ($total_estimate_time === " "))
						{
							setcookie("TotalEstimateTime","EmptyTotalEstimateTime");
							header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
						}
						else 
						{
							$status = $_POST['apt_status'];
							if (empty($status) or ($status === " "))
							{
								setcookie("Status","EmptyStatus");
								header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
							}
							else 
							{
								$car_id = $_POST['apt_selectedCarId'];
								if (empty($car_id) or ($car_id === " "))
								{
									setcookie("CarId","EmptyCarId");
									header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
								}
								else 
								{
									$procedures = explode(",",$_POST['apt_selectedProcList']);
									if (empty($procedures) or ($procedures === " "))
									{
										setcookie("Procedure","EmptyProcedure");
										header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
									}
									else 
									{
										$appointmentArray = array(':profile_id'=>$clientId, ':date'=>$date, ':start_time'=>$start_time, ':end_time'=>$end_time, 
											':total_estimate_time'=>$total_estimate_time, ':status'=>$status, ':car_id'=>$car_id);
										$modelAppointment = new Model_Appointment();
										$id = $modelAppointment->createNewAppointment($appointmentArray, $procedures);
										if ($id != -1)
										{
											if ($id == -2)
											{
												setcookie("Conflict","AppointmentConflict");
												header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
											}
											else 
											{
												session_start();
												$_SESSION['client_id'] = $clientId;
												$_SESSION['date'] = $_POST['currentDate'];
												$_SESSION['appointmentId'] = $id;
												session_write_close();
												header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/create');
											}
										}
										else 
										{
											setcookie("CreateAppointment","Unsuccessful");
											header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
}
function updateAppointment()
{
	clearAppointmentCookies();
	$appointment = getAppointmentArray();
	if (empty($appointment))
	{
		header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
	}
	else
	{
		$procedures = explode(",",$_POST['apt_selectedProcList']);
		$modelAppointment = new Model_Appointment();
		$count = $modelAppointment->updateAppointment($appointment, $procedures);
		if ($count !== 0)
		{
			session_start();
			$_SESSION['searchProfilePhone'] = $_POST['searchInput'];
			$_SESSION['date'] = $_POST['currentDate'];
			$_SESSION['appointmentId'] = $appointment[':appointment_id'];
			session_write_close();
			header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/selected');
		}
		else if ($count === 0)
		{
			setcookie("UpdateAppointment","Unsuccessful");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
		}
	}
}
function deleteAppointment()
{
	clearAppointmentCookies();
	$id = checkCtype_Digit($_POST['selectedAppointmentId']);
	if (empty($id) or $id === " ")
	{
		return null;
	}
	else
	{
		$modelPerson = new Model_Appointment();
		$count = $modelPerson->deleteAppointment($id);
		if ($count === 1)
		{
			session_start();
			if (isset($_SESSION['client_id']))
			{
				unset($_SESSION['client_id']);
			}
			if (isset($_SESSION['appointmentId']))
			{
				unset($_SESSION['appointmentId']);
			}
			if (isset($_SESSION['selectedCarIndex']))
			{
				unset($_SESSION['selectedCarIndex']);
			}
			if (isset($_SESSION['client_phone']))
			{
				unset($_SESSION['client_phone']);
			}
			$_SESSION['searchProfilePhone'] = $_POST['searchInput'];
			$_SESSION['date'] = $_POST['currentDate'];
			$_SESSION['lastURI'] = $_SERVER['REQUEST_URI'];
			session_write_close();
			header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/search');
		}
		else 
		{
			setcookie("DeleteAppointment","Unsuccessful");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
		}
	}
}
function selectedAppointment()
{
	$appointmentId = checkCtype_Digit($_POST['selectedAppointmentId']);
	if (empty($appointmentId) or ($appointmentId === " "))
	{
		return null;
	}
	else
	{
		session_start();
		$_SESSION['appointmentId'] = $appointmentId;
		$_SESSION['date'] = $_POST['currentDate'];
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/selected');
	}
}
function selectedAppointmentCar()
{
	$carId = checkCtype_Digit($_POST['selectedCarIndex']);
	$phone = $_POST['client_phone'];
	if(empty($phone) or ($phone === " ") or empty($carId) or ($carId === " "))
	{
		return null;
	}
	else
	{
		session_start();
		$_SESSION['selectedCarIndex'] = $carId;
		$_SESSION['client_phone'] = $phone;
		$_SESSION['date'] = $_POST['currentDate'];
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/car');
	}
}
function nextWeekAppointments()
{
	$appointmentId = checkCtype_Digit($_POST['selectedAppointmentId']);
	$date = $_POST['currentDate'];
	$targetProfile = $_POST['searchInput'];
	session_start();
	$_SESSION['appointmentId'] = $appointmentId;
	$_SESSION['searchProfilePhone'] = $targetProfile;
	$md = strtotime($date);
	$date = date('Y-m-d', mktime(date('h',$md),date('i',$md), date('s',$md), date('m',$md),date('d',$md)+7, date('Y',$md)));
	$_SESSION['date'] = $date;
	session_write_close();
	if(empty($targetProfile) or ($targetProfile === " "))
	{
		header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/week');
	}
	else
	{
		if ($_POST['appointmentAction'] === 'setSelectedAppointment' or (!empty($appointmentId)))
		{
			header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/selected');
		}
		else
		{
			header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/search');
		}
	}
}
function lastWeekAppointments()
{
	$appointmentId = checkCtype_Digit($_POST['selectedAppointmentId']);
	$date = $_POST['currentDate'];
	$targetProfile = $_POST['searchInput'];
	session_start();
	$_SESSION['appointmentId'] = $appointmentId;
	$_SESSION['searchProfilePhone'] = $targetProfile;
	$md = strtotime($date);
	$date = date('Y-m-d', mktime(date('h',$md),date('i',$md), date('s',$md), date('m',$md),date('d',$md)-7, date('Y',$md)));
	$_SESSION['date'] = $date;
	session_write_close();
	if(empty($targetProfile) or ($targetProfile === " "))
	{
		header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/week');
	}
	else
	{
		if ($_POST['appointmentAction'] === 'setSelectedAppointment' or (!empty($appointmentId)))
		{
			header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/selected');
		}
		else
		{
			header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/search');
		}
	}
}
function endAppointment()
{
	$appointmentId = checkCtype_Digit($_POST['selectedAppointmentId']);
	$car_id = $_POST['apt_selectedCarId'];
	if (empty($car_id) or ($car_id === " ") or empty($appointmentId) or ($appointmentId === " "))
	{
		return null;
	}
	$procedureList = explode(",",$_POST['apt_selectedProcNameList']);

	$modelAppointment = new Model_Appointment();
	$end = $modelAppointment->endAppointment($appointmentId,$car_id,$procedureList);
	if ($end === true)
	{
		session_start();
		if (isset($_SESSION['searchProfilePhone']))
		{
			unset($_SESSION['searchProfilePhone']);
		}
		if (isset($_SESSION['client_id']))
		{
			unset($_SESSION['client_id']);
		}
		if (isset($_SESSION['appointmentId']))
		{
			unset($_SESSION['appointmentId']);
		}
		if (isset($_SESSION['selectedCarIndex']))
		{
			unset($_SESSION['selectedCarIndex']);
		}
		if (isset($_SESSION['client_phone']))
		{
			unset($_SESSION['client_phone']);
		}
		if (isset($_SESSION['date']))
		{
			unset($_SESSION['date']);
		}
		if (isset($_SESSION['lastURI']))
		{
			unset($_SESSION['lastURI']);
		}
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'appointment/');
	}
	else 
	{
		setcookie("EndAppointment","Unsuccessful");
		header('Location: '.html($_SERVER['REQUEST_URI']));
	}
}
function clearAppointmentCookies()
{
	if (isset($_COOKIE["AppointmentPhone"]))
	{
		setcookie('AppointmentPhone');
	}
	if (isset($_COOKIE["SearchAppointment"]))
	{
		setcookie('SearchAppointment');
	}
	if (isset($_COOKIE["Date"]))
	{
		setcookie('Date');
	}
	if (isset($_COOKIE["StartTime"]))
	{
		setcookie('StartTime');
	}
	if (isset($_COOKIE["EndTime"]))
	{
		setcookie('EndTime');
	}
	if (isset($_COOKIE["TimeSlot"]))
	{
		setcookie('TimeSlot');
	}
	if (isset($_COOKIE["TotalEstimateTime"]))
	{
		setcookie('TotalEstimateTime');
	}
	if (isset($_COOKIE["Status"]))
	{
		setcookie('Status');
	}
	if (isset($_COOKIE["CarId"]))
	{
		setcookie('CarId');
	}
	if (isset($_COOKIE["Procedure"]))
	{
		setcookie('Procedure');
	}
	if (isset($_COOKIE["Conflict"]))
	{
		setcookie('Conflict');
	}
	if (isset($_COOKIE["CreateAppointment"]))
	{
		setcookie('CreateAppointment');
	}
	if (isset($_COOKIE["UpdateAppointment"]))
	{
		setcookie('UpdateAppointment');
	}
	if (isset($_COOKIE["DeleteAppointment"]))
	{
		setcookie('DeleteAppointment');
	}
	if (isset($_COOKIE["EndAppointment"]))
	{
		setcookie('EndAppointment');
	}
}
//Notification
function updateNotification()
{
	clearNotificationCookies();
	$notificationId = $_POST['notification_id'];
	$notificationMsg = checkCtype_Print($_POST['note_message']);
	$notificationSelected = $_POST['notification_selected'];
	echo $notificationId;
	echo $notificationMsg;
	echo $notificationSelected;
	if (empty($notificationMsg) or ($notificationMsg === " "))
	{
		setcookie("NotificationMsg","EmptyNotificationMsg");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'notification/');
	}
	else 
	{
		$notificationArray = array(':notification_id'=>$notificationId, ':notification_message'=>$notificationMsg);
		$modelNotification = new Model_Notification();
		$id = $modelNotification->updateNotificationTemplate($notificationArray);
		if ($id !== 0)
		{
			session_start();
			$_SESSION['notification_selected'] = $notificationSelected;
			session_write_close();
			header('Location: '.html($_SERVER['HTTP_ROOT']).'notification/edited');
		}
		else if ($id === 0)
		{
			setcookie("UpdateNotification","Unsuccessful");
			//header('Location: '.html($_SERVER['HTTP_ROOT']).'notification/');
		}
	}
}
function sendNotification()
{
	clearNotificationCookies();
	$modelNotification = new Model_Notification();
	$allEmails = $modelNotification->promotionalNotificationEmailList();
	$allPhones = $modelNotification->promotionalNotificationPhoneList();
	$subject = checkCtype_Print($_POST['subject']);
	$body = checkCtype_Print($_POST['content']);
	
	if (empty($subject) or ($subject === " "))
	{
		setcookie("NotificationSubject","EmptyNotificationSubject");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'notification/');
	}
	else 
	{
		if (empty($body) or ($body === " "))
		{
			setcookie("NotificationBody","EmptyNotificationBody");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'notification/');
		}
		else 
		{
			//
			$phoneHeader = "From: Garage E.K.A. Team <e.k.a@eka.com>\r\n";
			$header = "Reply-To: E.K.A. Team <e.k.a@eka.com>\r\n";
			$header .= "Return-Path: E.K.A. Team <e.k.a@eka.com>\r\n";
			$header .= $phoneHeader;
			$header .= "Organization: Garage E.K.A\r\n";
			$header .= "MIME-version: 1.0\r\n";
			$header .= "Content-type: text/html; charset= iso-8859-1\r\n";
	
			if (mailMan($allEmails, $subject, $body, $header) and smsMan($allPhones, $body, $phoneHeader))
			{
				header('Location: '.html($_SERVER['HTTP_ROOT']).'notification/sent');
			}
			else 
			{
				setcookie("SendNotification","Unsuccessful");
				header('Location: '.html($_SERVER['HTTP_ROOT']).'notification/');
			}
		}
	}
}
function sendAutomaticNotification()
{
	$modelNotification = new Model_Notification();
	$notifications = $modelNotification->getAllNotificationTypes();
	$phoneHeader = "From: Garage E.K.A. Team <e.k.a@eka.com>\r\n";
	$header = "Reply-To: E.K.A. Team <e.k.a@eka.com>\r\n";
	$header .= "Return-Path: E.K.A. Team <e.k.a@eka.com>\r\n";
	$header .= $phoneHeader;
	$header .= "Organization: Garage E.K.A\r\n";
	$header .= "MIME-version: 1.0\r\n";
	$header .= "Content-type: text/html; charset= iso-8859-1\r\n";
	foreach ($notifications as $notification)
	{
		if ($notification->getNotificationId() == 1)
		{
			$allEmails = $modelNotification->appointmentNotificationEmailList();
			$allPhones = $modelNotification->appointmentNotificationPhoneList();
			$subject = "Appointment Reminder";
			$body = $notification->getNotificationMessage();
			//			
			mailMan($allEmails, $subject, $body, $header);
			smsMan($allPhones, $body, $phoneHeader);
		}
		elseif ($notification->getNotificationId() == 2)
		{
			$allEmails = $modelNotification->maintenenceNotificationEmailList();
			$allPhones = $modelNotification->maintenenceNotificationPhoneList();
			$subject = "Maintenance Notification";
			$body = $notification->getNotificationMessage();
			//				
			mailMan($allEmails, $subject, $body, $header);
			smsMan($allPhones, $body, $phoneHeader);
		}
	}
}
function clearNotificationCookies()
{
	if (isset($_COOKIE["NotificationMsg"]))
	{
		setcookie('NotificationMsg');
	}
	if (isset($_COOKIE["NotificationSubject"]))
	{
		setcookie('NotificationSubject');
	}
	if (isset($_COOKIE["NotificationBody"]))
	{
		setcookie('NotificationBody');
	}
	if (isset($_COOKIE["SendNotification"]))
	{
		setcookie('SendNotification');
	}
	if (isset($_COOKIE["UpdateNotification"]))
	{
		setcookie('UpdateNotification');
	}
}
//report
function procedurePerformedReport()
{
	clearReportCookies();
	$startDate = $_POST['startDate'];
	$endDate = $_POST['endDate'];
	if(empty($startDate) or ($startDate === " "))
	{
		setcookie("StartDate","EmptyStartDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (!checkDateFormat($startDate))
	{
		setcookie("StartDate","InvalidStartDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (empty($endDate) or ($endDate === " "))
	{
		setcookie("EndDate","EmptyEndDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (!checkDateFormat($endDate))
	{
		setcookie("EndDate","InvalidEndDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else
	{
		session_start();
		$_SESSION['startDate'] = $startDate;
		$_SESSION['endDate'] = $endDate;
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/procedureperformed');
	}
}
function inventoryNeededReport()
{
	clearReportCookies();
	$startDate = $_POST['startDate'];
	$endDate = $_POST['endDate'];
	if(empty($startDate) or ($startDate === " "))
	{
		setcookie("StartDate","EmptyStartDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (!checkDateFormat($startDate))
	{
		setcookie("StartDate","InvalidStartDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (empty($endDate) or ($endDate === " "))
	{
		setcookie("EndDate","EmptyEndDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (!checkDateFormat($endDate))
	{
		setcookie("EndDate","InvalidEndDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else
	{
		session_start();
		$_SESSION['startDate'] = $startDate;
		$_SESSION['endDate'] = $endDate;
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/inventoryneeded');
	}
}
function inventoryUsedReport()
{
	clearReportCookies();
	$startDate = $_POST['startDate'];
	$endDate = $_POST['endDate'];
	if(empty($startDate) or ($startDate === " "))
	{
		setcookie("StartDate","EmptyStartDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (!checkDateFormat($startDate))
	{
		setcookie("StartDate","InvalidStartDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (empty($endDate) or ($endDate === " "))
	{
		setcookie("EndDate","EmptyEndDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (!checkDateFormat($endDate))
	{
		setcookie("EndDate","InvalidEndDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else
	{
		session_start();
		$_SESSION['startDate'] = $startDate;
		$_SESSION['endDate'] = $endDate;
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/inventoryused');
	}
}
function appointmentHoursReport()
{
	clearReportCookies();
	$startDate = $_POST['startDate'];
	$endDate = $_POST['endDate'];
	if(empty($startDate) or ($startDate === " "))
	{
		setcookie("StartDate","EmptyStartDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (!checkDateFormat($startDate))
	{
		setcookie("StartDate","InvalidStartDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (empty($endDate) or ($endDate === " "))
	{
		setcookie("EndDate","EmptyEndDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else if (!checkDateFormat($endDate))
	{
		setcookie("EndDate","InvalidEndDate");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/');
	}
	else
	{
		session_start();
		$_SESSION['startDate'] = $startDate;
		$_SESSION['endDate'] = $endDate;
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'report/appointmenthours');
	}
}
function clearReportCookies()
{
	if (isset($_COOKIE["StartDate"]))
	{
		setcookie('StartDate');
	}
	if (isset($_COOKIE["EndDate"]))
	{
		setcookie('EndDate');
	}
}
//procedure
function selectedProcProcedure()
{
	clearProcedureCookies();
	$procedureId = checkCtype_Digit($_POST['selectedProcId']);
	if(empty($procedureId) or ($procedureId === " "))
	{
		return null;
	}
	else
	{
		session_start();
		$_SESSION['selectedProcId'] = $procedureId;
		session_write_close();
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/selected');
	}
}
function updateProcProcedure()
{
	clearProcedureCookies();
	$procedureId = checkCtype_Digit($_POST['selectedProcId']);
	if(empty($procedureId) or ($procedureId === " "))
	{
		return null;
	}
	$procedure = explode(",",$_POST['proc_procedure']);
	if(empty($procedure) or ($procedure === false))
	{
		setcookie("ProcProcedure","EmptyProcProcedure");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
	else if (empty($procedure[1]))
	{
		setcookie("ProcProcedureName","EmptyProcProcedureName");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
	else if ($procedure[2] < 0)
	{
		setcookie("ProcProcedureDuration","NegativeProcProcedureDuration");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
	else if ( (checkCtype_Digit($procedure[2]) === null) or (checkCtype_Digit($procedure[2])%15) != 0)
	{
		setcookie("ProcProcedureDuration","InvalidProcProcedureDuration");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
	else if (empty($procedure[2]))
	{
		setcookie("ProcProcedureDuration","EmptyProcProcedureDuration");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
	else 
	{
		$itemsList = explode(",",$_POST['proc_itemList']);
		if(empty($itemsList) or ($itemsList === false) or (!isset($itemsList[0])) or empty($itemsList[0]))
		{
			setcookie("ProcItemsList","EmptyProcItemsList");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
		}
		else 
		{
			$quantityList = explode(",",$_POST['proc_quantityList']);
			if(empty($quantityList) or ($quantityList === false))
			{
				setcookie("ProcQuantityList","EmptyProcQuantityList");
				header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
			}
			else 
			{
				foreach ($quantityList as $quantity)
				{
					if ($quantity < 0)
					{
						setcookie("ProcQuantityList","NegativeProcQuantityList");
						header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
						return;
					}
					else if (checkCtype_Digit($quantity) === null)
					{
						setcookie("ProcQuantityList","InvalidProcQuantityList");
						header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
						return;
					}
				}
				$modelProcedure = new Model_Procedure();
				$count = $modelProcedure->updateProcedure($procedure,$itemsList,$quantityList);
				if($count != -1)
				{
					session_start();
					$_SESSION['selectedProcId'] = $procedureId;
					session_write_close();
					header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/selected');
				}
				else 
				{
					setcookie("UpdateProcProcedure","Unsuccessful");
					header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
				}
			}
		}
	}
}
function deleteProcProcedure()
{
	clearProcedureCookies();
	$procedureId = checkCtype_Digit($_POST['selectedProcId']);
	if(empty($procedureId) or ($procedureId === " "))
	{
		return null;
	}
	else
	{
		$modelProcedure = new Model_Procedure();
		$id = $modelProcedure->deleteProcedure($procedureId);
		if($id != -1)
		{
			session_start();
			if (isset($_SESSION['selectedProcId']))
			{
				unset($_SESSION['selectedProcId']);
			}
			session_write_close();
		}
		else 
		{
			setcookie("DeleteProcProcedure","Unsuccessful");
		}
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
}
function createProcProcedure()
{
	clearProcedureCookies();
	$procedure = explode(",",$_POST['proc_procedure']);
	if(empty($procedure) or ($procedure === false))
	{
		setcookie("ProcProcedure","EmptyProcProcedure");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
	else if (empty($procedure[1]))
	{
		setcookie("ProcProcedureName","EmptyProcProcedureName");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
	else if ($procedure[2] < 0)
	{
		setcookie("ProcProcedureDuration","NegativeProcProcedureDuration");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
	else if ((checkCtype_Digit($procedure[2]) === null) or (checkCtype_Digit($procedure[2])%15) != 0)
	{
		setcookie("ProcProcedureDuration","InvalidProcProcedureDuration");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
	else if (empty($procedure[2]))
	{
		setcookie("ProcProcedureDuration","EmptyProcProcedureDuration");
		header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
	}
	else 
	{
		$itemsList = explode(",",$_POST['proc_itemList']);
		if(empty($itemsList) or ($itemsList === false) or (!isset($itemsList[0])) or empty($itemsList[0]))
		{
			setcookie("ProcItemsList","EmptyProcItemsList");
			header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
		}
		else
		{
			$quantityList = explode(",",$_POST['proc_quantityList']);
			if(empty($quantityList) or ($quantityList === false))
			{
				setcookie("ProcQuantityList","EmptyProcQuantityList");
				header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
			}
			else
			{
				foreach ($quantityList as $quantity) 
				{
					if ($quantity < 0)
					{
						setcookie("ProcQuantityList","NegativeProcQuantityList");
						header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
						return;
					}
					else if (checkCtype_Digit($quantity) === null)
					{
						setcookie("ProcQuantityList","InvalidProcQuantityList");
						header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
						return;
					}
				}
				$modelProcedure = new Model_Procedure();
				$id = $modelProcedure->createNewProcedure($procedure,$itemsList,$quantityList);
				if($id != -1)
				{
					session_start();
					$_SESSION['selectedProcId'] = $id;
					session_write_close();
					header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/selected');
				}
				else 
				{
					setcookie("CreateProcProcedure","Unsuccessful");
					header('Location: '.html($_SERVER['HTTP_ROOT']).'procedure/');
				}
			}
		}
	}
}
function clearProcedureCookies()
{
	if (isset($_COOKIE["ProcProcedure"]))
	{
		setcookie('ProcProcedure');
	}
	if (isset($_COOKIE["ProcProcedureName"]))
	{
		setcookie('ProcProcedureName');
	}
	if (isset($_COOKIE["ProcProcedureDuration"]))
	{
		setcookie('ProcProcedureDuration');
	}
	if (isset($_COOKIE["ProcItemsList"]))
	{
		setcookie('ProcItemsList');
	}
	if (isset($_COOKIE["ProcQuantityList"]))
	{
		setcookie('ProcQuantityList');
	}
	if (isset($_COOKIE["UpdateProcProcedure"]))
	{
		setcookie('UpdateProcProcedure');
	}
	if (isset($_COOKIE["DeleteProcProcedure"]))
	{
		setcookie('DeleteProcProcedure');
	}
	if (isset($_COOKIE["CreateProcProcedure"]))
	{
		setcookie('CreateProcProcedure');
	}
}

//
function getSupplierArray()
{
	//validate and filter user data
	$name = $_POST['newSupplierName'];
	$phone = $_POST['newSupplierPhone'];
	$id = checkCtype_Digit($_POST['supplierSelectedId']);
	
	if (empty($name) or ($name === " "))
	{
		setcookie("SupplierName","EmptyName");
		return array();
	}
	else if (empty($phone) or ($phone === " ") or (!checkPhoneFormat($phone)))
	{
		setcookie("SupplierPhone","InvalidPhone");
		return array();
	}
	else if (empty($id) or ($id === " "))
	{
		return array();
	}
	else
	{
		// skills value
		return array(':supplier_name' => $name, ':supplier_phone' => $phone, ':supplier_id' => $id);
	}
}
function getInventoryArray()
{
	//validate and filter user data
	$product_name = $_POST['newItemName'];
	$product_description = $_POST['newItemDescription'];
	$product_quantity = checkCtype_Digit($_POST['newItemQuantity']);
	$id = checkCtype_Digit($_POST['inventorySelectedId']);
	if (empty($product_name) or ($product_name === " "))
	{
		setcookie("ProductName","EmptyName");
		return array();
	}
	else if (empty($product_description) or ($product_description === " "))
	{
		setcookie("ProductDescription","EmptyDescription");
		return array();
	}
	else if ( $product_quantity === null)
	{
		setcookie("ProductQuantity","InvalidQuantity");
		return array();
	}
	else if ( empty($product_quantity) or ($product_quantity === " "))
	{
		setcookie("ProductQuantity","EmptyQuantity");
		return array();
	}
	else if ( $product_quantity < 0)
	{
		setcookie("ProductQuantity","NegativeQuantity");
		return array();
	}
	else if (empty($id) or ($id === " "))
	{
		return array();
	}
	else
	{
		// quantity value
		return array(':product_quantity' => $product_quantity, ':product_description' => $product_description, ':product_name' => $product_name, ':product_id'=> $id);
	}
}
function getProfileArray()
{
	if (!isset($_POST['c_sex']))
	{
		setcookie("ProfileGender","EmptyGender");
		return array();
	}
	else
	{
		if ($_POST['c_sex'] === "Male")
		{
			$gender = 'M';
		}
		else
		{
			$gender = 'F';
		}
	}
	$first_name = $_POST['c_fname'];
	if (empty($first_name) or ($first_name === " "))
	{
		setcookie("ProfileFName","EmptyFName");
		return array();
	}
	$last_name = $_POST['c_lname'];
	if (empty($last_name) or ($last_name === " "))
	{
		setcookie("ProfileLName","EmptyLName");
		return array();
	}
	$home_phone_number = $_POST['c_hphone'];
	if (!checkPhoneFormat($home_phone_number))
	{
		setcookie("ProfileHomePhone","InvalidPhone");
		return array();
	}
	$email = checkCtype_Email($_POST['c_email']);
	$role = null;
	$cell_phone_number = $_POST['c_cphone'];
	if (!checkPhoneFormat($cell_phone_number))
	{
		setcookie("ProfileCellPhone","InvalidPhone");
		return array();
	}
	//
	$person_id = checkCtype_Digit($_POST['personId']);
	if (empty($person_id) or ($person_id === " "))
	{
		return array();
	}
	$profile_id = checkCtype_Digit($_POST['client_id']);
	if (empty($profile_id) or ($profile_id === " "))
	{
		return array();
	}
	$modification_date = date("Y-m-d");
	
	$carrier = $_POST['cell_phone_carrier'];
	if(isset($_POST['sendNoteToCell']))
	{
		$send_to_cell_phone = 1;
		$cell_phone_carrier = sendTextToPhoneAddress($cell_phone_number, $carrier);
	}
	else
	{
		$send_to_cell_phone = 0;
		$cell_phone_carrier = null;
	}
	
	if(isset($_POST['sendNoteToEmail']))
	{
		$send_to_email = 1;
	}
	else
	{
		$send_to_email = 0;
	}
	
	if ($_POST['note0'] === "Yes")
	{
		$tire_set_stored = 1;
	}
	else
	{
		$tire_set_stored = 0;
	}
	if ($_POST['note1'] === "Yes")
	{
		$note1 = 1;
	}
	else
	{
		$note1 = 0;
	}
	if ($_POST['note2'] === "Yes")
	{
		$note2 = 1;
	}
	else
	{
		$note2 = 0;
	}
	if ($_POST['note3'] === "Yes")
	{
		$note3 = 1;
	}
	else
	{
		$note3 = 0;
	}
	
	return array(':person_id' => $person_id, ':first_name'=>$first_name, ':last_name'=>$last_name, ':home_phone_number'=>$home_phone_number, ':email'=>$email, 
			':role'=> $role, ':gender'=>$gender,':cell_phone_number'=>$cell_phone_number, ':cell_phone_carrier'=>$cell_phone_carrier,
			':profile_id' => $profile_id, ':tire_set_stored' => $tire_set_stored, ':modification_date' => $modification_date,
			':send_to_cell_phone' => $send_to_cell_phone, ':send_to_email' => $send_to_email, ':note1' => $note1,
			':note2' => $note2, ':note3' => $note3);
}
function getCarArray()
{
	$car_history = $_POST['carHistory'];
	if (empty($car_history) or ($car_history === " "))
	{
		setcookie("CarHistory","EmptyHistory");
		return array();
	}
	$make = $_POST['carMake'];
	if (empty($make) or ($make === " "))
	{
		setcookie("CarMake","EmptyMake");
		return array();
	}
	$model = $_POST['carModel'];
	if (empty($model) or ($model === " "))
	{
		setcookie("CarModel","EmptyModel");
		return array();
	}
	$year = checkCtype_Digit($_POST['carYear']);
	if (empty($year) or ($year === " "))
	{
		setcookie("CarYear","EmptyYear");
		return array();
	}
	else if (($year === null) or (strlen($year) !== 4) or ($year > checkCtype_Digit(date("Y"))))
	{
		setcookie("CarYear","InvalidYear");
		return array();
	}
	$last_oil_change_date = $_POST['lastOilChanged'];
	if ( ((!empty($last_oil_change_date)) or (!$last_oil_change_date === " ")) and (!checkDateFormat($last_oil_change_date)) )
	{
		setcookie("LastOilChangeDate","InvalidLastOilChangeDate");
		return array();
	}
	$id = checkCtype_Digit($_POST['carSelectedId']);
	$profileId = checkCtype_Digit($_POST['client_id']);
	if (empty($id) or ($id === " ") or empty($profileId) or ($profileId === " "))
	{
		return array();
	}
	else
	{
		return array(':profile_id' => $profileId, ':car_id' => $id, ':car_history'=>$car_history, ':make'=>$make, ':model'=>$model, ':year'=>$year,
			':last_oil_change_date'=> $last_oil_change_date);
	}
}
function getAppointmentArray()
{
	$date = $_POST['apt_appointmentDate'];
	if (empty($date) or ($date === " ") or ($date === "0000-00-00"))
	{
		setcookie("Date","EmptyDate");
		return array();
	}
	else if (!checkDateFormat($date) or (strtotime($date) < time())) 
	{
		setcookie("Date","InvalidDate");
		return array();
	}
	$start_time = $_POST['apt_startTime'];
	if (empty($start_time) or ($start_time === " "))
	{
		setcookie("StartTime","EmptyStartTime");
		return array();
	}
	$end_time = $_POST['apt_endTime'];
	if (empty($end_time) or ($end_time === " "))
	{
		setcookie("EndTime","EmptyEndTime");
		return array();
	}
	$total_estimate_time = $_POST['apt_estTime'];
	if (empty($total_estimate_time) or ($total_estimate_time === " "))
	{
		setcookie("TotalEstimateTime","EmptyTotalEstimateTime");
		return array();
	}
	$status = $_POST['apt_status'];
	if (empty($status) or ($status === " "))
	{
		setcookie("Status","EmptyStatus");
		return array();
	}
	$car_id = $_POST['apt_selectedCarId'];
	if (empty($car_id) or ($car_id === " "))
	{
		setcookie("CarId","EmptyCarId");
		return array();
	}
	$clientId = checkCtype_Digit($_POST['apt_clientId']);
	$id = checkCtype_Digit($_POST['selectedAppointmentId']);
	if (empty($clientId) or ($clientId === " ") or empty($id) or ($id === " "))
	{
		return array();
	}
	else
	{
		return array(':profile_id'=>$clientId, ':appointment_id'=>$id, ':date'=>$date, ':start_time'=>$start_time, ':end_time'=>$end_time, 
			':total_estimate_time'=>$total_estimate_time, ':status'=>$status, ':car_id'=>$car_id);
	}
}
function clearAllCookies()
{
	clearSupplierCookies();
	clearInventoryCookies();
	clearProfileCookies();
	clearAppointmentCookies();
	clearNotificationCookies();
	clearReportCookies();
	clearProcedureCookies();
}

//
function checkCtype_Print($text)
{
	if(!empty($text) and ctype_print($text))
	{
		return $text;
	}
	else
	{
		return (string)$text;
	}
}
function checkCtype_Email($email)
{
	if(!empty($email) and ctype_print($email) and filter_var($email, FILTER_VALIDATE_EMAIL))
	{
		return $email;
	}
	else
	{
		return null;
	}
}
function checkCtype_Digit($digit)
{
	if(!empty($digit) and ctype_digit($digit))
	{
		return $digit;
	}
	else
	{
		return null;
	}
}
function checkPhoneFormat($rawPhone)
{
	//validate phone format with two dash xxxx-xxx-xxxx
	if ( (strpos($rawPhone,'-') === 4) and (strpos($rawPhone,'-', 8) === 8) )
	{
		$phone = explode("-",$rawPhone);
		if (empty($phone) || ($phone === false) || (strlen($phone[0]) > 4) 
			|| (strlen($phone[1]) > 3) || (strlen($phone[2]) > 4) || (substr($phone[0], 0, 1) != 1))
		{
			return false;
		}
		else 
		{
			//validate phone is composed of only digits
			if ( (checkCtype_Digit($phone[0]) === null) or (checkCtype_Digit($phone[1]) === null) or (checkCtype_Digit($phone[2]) === null) )
			{
				return false;
			}
			return true;
		}
	}
	else 
	{
		return false;
	}
}
function sendTextToPhoneAddress($cell_phone_number, $carrier)
{
	$phone = explode("-",$cell_phone_number);
	$phone0 = substr($phone[0], 1);
	$phoneAdress = " ";
	switch ($carrier)
	{
		case 'Bell':
			$phoneAdress = $phone0.$phone[1].$phone[2]."@txt.bell.ca";
			break;
		case 'Bell Mobility':
			$phoneAdress = $phone0.$phone[1].$phone[2]."@txt.bellmobility.ca";
			break;
		case 'Fido':
			$phoneAdress = $phone0.$phone[1].$phone[2]."@sms.fido.ca";
			break;
		case 'Rogers':
			$phoneAdress = $phone0.$phone[1].$phone[2]."@pcs.rogers.com";
			break;
		case 'Telus':
			$phoneAdress = $phone0.$phone[1].$phone[2]."@msg.telus.com";
			break;
		case 'Virgin Mobile':
			$phoneAdress = $phone0.$phone[1].$phone[2]."@vmobile.ca";
			break;
		case 'Koodo Mobile':
			$phoneAdress = $phone0.$phone[1].$phone[2]."@msg.koodomobile.com";
			break;
		default: $phoneAdress = null;
			break;
	}
	return $phoneAdress;
}
function checkDateFormat($rawDate)
{
	//validate date format with two dash xxxx-xx-xx
	if ( (strpos($rawDate,'-') === 4) and (strpos($rawDate,'-', 7) === 7) )
	{
		$date = explode("-",$rawDate);
		if (empty($date) || ($date === false) || (strlen($date[0]) > 4) || (strlen($date[1]) > 2) || (strlen($date[2]) > 2))
		{
			return false;
		}
		else
		{
			//validate date is composed of only digits
			if ( (checkCtype_Digit($date[0]) === null) or (checkCtype_Digit($date[1]) === null) or (!checkdate($date[1], $date[2], $date[0])) )
			{
				return false;
			}
			return true;
		}
	}
	else
	{
		return false;
	}
}
function smsMan($phones, $body, $header)
{
	foreach ($phones as $phone)
	{
		mail($phone['cell_phone_carrier'], "Dear ".$phone['first_name']." ".$phone['last_name'].",\r\n".$body, $header);
	}
	return true;
}
function mailMan($emails, $subject, $body, $header)
{
	foreach ($emails as $email)
	{
		sendEmail($email['email'], $subject, nl2br("Dear ".$email['first_name']." ".$email['last_name'].",\n".$body), $header);
	}
	return true;
}
function sendEmail($toEmail, $emailSubject, $messageBody, $mailheader)
{
	mail($toEmail, $emailSubject, $messageBody, $mailheader) or die ("Failure");
}